package pers.cyw.oraclejavaproject.util;

import pers.cyw.oraclejavaproject.domain.User;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


public class DBDo {
    private DBDo(){}
    //    查找所有用户
    public static List<User> queryAll(){
        String sql = "select * from users";
        return ret(sql);
    }
    //    按字段查找
    public static List<User> queryBy(String key,Object value){
        String sql = "select * from users where " + key + " =  ?";
        return ret(sql,value);
    }
    // 模糊查询
    public  static  List<User> queryLike(String key,Object...value){
//        模糊数据为空则是查找全部
        if(value.length==0){
            return queryAll();
        }
        String sql = "select * from users where "+key+" like ?";
        return ret(sql,value);
    }
    //删除
    public static int delete(User u) {
        String sql = "delete from users where ID = ?";
        return JdbcTemplate.update(sql,u.getId());
    }
    //修改
    public static int update(User u) {
        String sql = "update  users set NAME=?,PASSWORD=?,SEX=? where ID = ?";
        return JdbcTemplate.update(sql,u.getName(),u.getPassword(),u.getSex(),u.getId());
    }
    //添加
    public static int add(User u) {
        String sql = "insert  into users where (NAME ,PASSWORD,SEX) values (?,?,?)";
        return JdbcTemplate.update(sql,u.getName(),u.getPassword(),u.getSex());
    }

    //返回查询结果
    private static List<User> ret(String sql,Object...value){
        return JdbcTemplate.query(sql,(rs) -> {
            List<User> list = new ArrayList<>();
            while (rs.next()){
                list.add(new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),LocalDateTime.now()));
            }
            return list;
        },value);
    }
}
